package com.rub.prajna.core.utils

class EscapeUnescape {

    /**
     * 编码
     */
    fun escape(src: String): String? {
        var j: Char
        val buffer = StringBuffer()
        buffer.ensureCapacity(src.length * 6)
        var i: Int = 0
        while (i < src.length) {
            j = src[i]
            if (Character.isDigit(j) || Character.isLowerCase(j)
                || Character.isUpperCase(j)
            ) buffer.append(j) else if (j.code < 256) {
                buffer.append("%")
                if (j.code < 16) buffer.append("0")
                buffer.append(j.code.toString(16))
            } else {
                buffer.append("%u")
                buffer.append(j.code.toString(16))
            }
            i++
        }
        return buffer.toString()
    }

    /**
     * 解码
     */
    fun unescape(src: String): String? {
        val buffer = StringBuffer()
        buffer.ensureCapacity(src.length)
        var lastPos = 0
        var pos = 0
        var ch: Char
        while (lastPos < src.length) {
            pos = src.indexOf("%", lastPos)
            if (pos == lastPos) {
                if (src[pos + 1] == 'u') {
                    ch = src
                        .substring(pos + 2, pos + 6).toInt(16).toChar()
                    buffer.append(ch)
                    lastPos = pos + 6
                } else {
                    ch = src
                        .substring(pos + 1, pos + 3).toInt(16).toChar()
                    buffer.append(ch)
                    lastPos = pos + 3
                }
            } else {
                lastPos = if (pos == -1) {
                    buffer.append(src.substring(lastPos))
                    src.length
                } else {
                    buffer.append(src.substring(lastPos, pos))
                    pos
                }
            }
        }
        return buffer.toString()
    }
}